package io.modifier.basic.emo.permission

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import android.view.View
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import io.modifier.basic.emo.modal.EmoModal
import io.modifier.basic.emo.modal.emoModal
import io.modifier.basic.emo.ui.core.ex.findActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

internal class EmoPermissionModal(
    private val view: View,
    private val scope: CoroutineScope,
    private val tip: EmoPermissionTip,
) {

    private var modal: EmoModal? = null
    private var launchJob: Job? = null

    fun launch() {
        dismiss()
        launchJob = scope.launch(Dispatchers.Main) {
            if (view.isAttachedToWindow) {
                modal = view.emoModal(
                    mask = Color.Transparent,
                    enter = fadeIn(),
                    exit = fadeOut(),
                ) {
                    tip.run {
                        Content()
                    }
                }.show()
            }
        }
    }

    fun dismiss() {
        launchJob?.cancel()
        launchJob = null
        modal?.dismiss()
        modal = null
    }

    fun showNotAvailableTip() {
        dismiss()
        launchJob = scope.launch(Dispatchers.Main) {
            if (view.isAttachedToWindow) {
                modal = view.emoModal(
                    mask = Color.Transparent,
                    enter = fadeIn(),
                    exit = fadeOut(),
                ) {
                    val ctx = LocalContext.current
                    tip.run {
                        NotAvailableContent {
                            ctx.findActivity()?.openAppSettings()
                            dismiss()
                        }
                    }
                }.show()
            }
        }
    }

    private fun Activity.openAppSettings() {
        Intent(
            Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
            Uri.fromParts("package", packageName, null)
        ).also(::startActivity)
    }
}
